package itbour.onetouchshow.activity.userinfo;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.utils.permission.Permission;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.UserDetailInfoBean;
import itbour.onetouchshow.bean.eventbus.UpdateUserAction;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.aliyun.AliRequestUtils;

import static itbour.onetouchshow.bean.eventbus.UpdateUserAction.UPDATA_USER_NAME;
import static itbour.onetouchshow.bean.eventbus.UpdateUserAction.UPDAT_USER_AV;
import static itbour.onetouchshow.bean.eventbus.UpdateUserAction.UPDAT_USER_SGIN;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class UserinfoActivity extends MVPBaseActivity<UserinfoContract.View, UserinfoPresenter> implements UserinfoContract.View {

    private final int uploadSuccess = 1;
    private final int stillUpload = 0;
    private final int uploadFail = -1;
    private final int PHONE_CAMERA = 1;
    private final int PHONE_CROP = 2;
    private final int SCAN_OPEN_PHONE = 3;
    @BindView(R.id.id_iv_av)
    ImageView idIvAv;
    @BindView(R.id.rl_pif_icon_advance)
    RelativeLayout rlPifIconAdvance;
    @BindView(R.id.id_tv_name)
    TextView idTvName;
    @BindView(R.id.iv_tv_sign)
    TextView ivTvSign;
    @BindView(R.id.rl_pif_sign_advance)
    RelativeLayout rlPifSignAdvance;
    UserDetailInfoBean userDetailInfoBean;
    @BindView(R.id.ly_name)
    LinearLayout lyName;
    @BindView(R.id.ly_sign)
    LinearLayout lySign;
    @BindView(R.id.id_iv_av_more)
    ImageView igIvMore;
    Uri mCutUri;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case uploadSuccess:
                case uploadFail:
                    dismissProgressDialog();
                    break;
                case stillUpload:
                    showProgressDialog();
                    break;
            }
        }
    };
    private String IMAGEFILETYPE = ".png";

    @Override
    public void loadSucceed(String result) {
        Message message = new Message();
        message.what = uploadSuccess;
        handler.sendMessage(message);
    }

    @Override
    public void loadFaild(String error) {
        Message message = new Message();
        message.what = uploadFail;
        handler.sendMessage(message);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("个人信息");
        // requestPermissions();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_userinfo;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            // userDetailInfoBean = extras.getParcelable("userDetailInfoBean");
            String userName = extras.getString("userName");
            String userSign = extras.getString("userSign");
            String avatarUrl = extras.getString("AvatarUrl");
            userDetailInfoBean = new UserDetailInfoBean();
            userDetailInfoBean.setUserInfo(new UserDetailInfoBean.UserInfoBean());
            userDetailInfoBean.getUserInfo().setNickName(userName);
            userDetailInfoBean.getUserInfo().setSign(userSign);
            userDetailInfoBean.getUserInfo().setAvatarUrl(avatarUrl);
        }
        if (userDetailInfoBean != null) {
            idTvName.setText(userDetailInfoBean.getUserInfo().getNickName());
            ivTvSign.setText(userDetailInfoBean.getUserInfo().getSign());
            ImageLoader.getInstance().showImage(UserinfoActivity.this, userDetailInfoBean.getUserInfo().getAvatarUrl(), idIvAv);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dataEvent(UpdateUserAction updateUserAction) {
        int subType = updateUserAction.getSubType();
        switch (subType) {
            case UPDAT_USER_SGIN:
                ivTvSign.setText(updateUserAction.getContent());
                break;
            case UPDATA_USER_NAME:
                idTvName.setText(updateUserAction.getContent());
                break;
            case UPDAT_USER_AV:
                ImageLoader.getInstance().showUserHead(UserinfoActivity.this, userDetailInfoBean.getUserInfo().getAvatarUrl(), idIvAv);
                break;
            default:
        }
        //EventBus.getDefault().post(updateUserAction);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 打开相册
     */
    private void cameraPic() {
        //创建一个file，用来存储拍照后的照片
        File outputfile = new File(UIUtils.getContext().getExternalCacheDir(), "output.png");
        try {
            if (outputfile.exists()) {
                outputfile.delete();//删除
            }
            outputfile.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Uri imageuri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            imageuri = FileProvider.getUriForFile(UserinfoActivity.this,
                    AppConst.PORVIDER,
                    outputfile);
        } else {
            imageuri = Uri.fromFile(outputfile);
        }
        //启动相机程序
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, SCAN_OPEN_PHONE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                //从相册图片后返回的uri
                case SCAN_OPEN_PHONE:
                    //启动裁剪
                    startActivityForResult(CutForPhoto(data.getData()), PHONE_CROP);
                    break;
                //相机返回的 uri
                case PHONE_CAMERA:
                    //启动裁剪
                    String path = UIUtils.getContext().getExternalCacheDir().getPath();
                    String name = "output.png";
                    startActivityForResult(CutForCamera(path, name), PHONE_CROP);
                    break;
                case PHONE_CROP:
                    try {
                        //获取裁剪后的图片，并显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(
                                UIUtils.getContext().getContentResolver().openInputStream(mCutUri));
                        // idIvAv.setImageBitmap(bitmap);
                        L_.e("temppathpathName " + "temppath" + mCutUri.getPath());
                        //上传阿里云
                        // upLoadAliyun();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    String imageUrl = null;
                    for (LocalMedia media : localMedia) {
                        Log.i("图片-----》", media.getPath());
                        imageUrl = media.getPath();
                    }
                    upLoadAliyun(imageUrl);
                    break;
            }
        }
    }

    public void upLoadAliyun(String imageUrl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String name1 = AliRequestUtils.getInstance().createFileName("image", App.getLoginBean().getUserInfo().getUserId() + "") + IMAGEFILETYPE;
                AliRequestUtils.getInstance().setName(name1);
                ///yjx/v1/user/updateUserInfo_v1_0
                try {
                    PutObjectRequest request = new PutObjectRequest(AppConst.OSSBUCKETNAME, AliRequestUtils.getInstance().getName(), imageUrl);
                    request.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                        @Override
                        public void onProgress(PutObjectRequest putObjectRequest, long l, long l1) {
                            if (l != l1) {
                                Message message = new Message();
                                message.what = stillUpload;
                                handler.sendMessage(message);
                            } else {
                                //上传完毕 等待请求接口上传个人数据 dialog依然显示
                            }
                        }
                    });
                    App.ossClient.putObject(request);
                    String pathName = AppConfig.UPLOAD_ALYUN + name1;
                    userDetailInfoBean.getUserInfo().setAvatarUrl(pathName);
                    UpdateUserAction updateUserAction = new UpdateUserAction();
                    updateUserAction.setSubType(UPDAT_USER_AV);
                    updateUserAction.setContent(pathName);
                    EventBus.getDefault().post(updateUserAction);
                    if (mPresenter != null) {
                        mPresenter.upDateUserInfo("", "", pathName);
                    }
                } catch (ClientException e) {
                    e.printStackTrace();
                    T_.showToastWhendebug("上传失败");
                } catch (ServiceException e) {
                    e.printStackTrace();
                    T_.showToastWhendebug("上传失败");
                }
            }
        }).start();
    }

    /**
     * 图片裁剪
     *
     * @param uri
     * @return
     */
    @NonNull
    private Intent CutForPhoto(Uri uri) {
        try {
            //直接裁剪
            Intent intent = new Intent("com.android.camera.action.CROP");
            //设置裁剪之后的图片路径文件
            File cutfile = new File(Environment.getExternalStorageDirectory().getPath(),
                    "cutcamera.png"); //随便命名一个
            if (cutfile.exists()) { //如果已经存在，则先删除,这里应该是上传到服务器，然后再删除本地的，没服务器，只能这样了
                cutfile.delete();
            }
            cutfile.createNewFile();
            //初始化 uri
            Uri imageUri = uri; //返回来的 uri
            Uri outputUri = null; //真实的 uri
            outputUri = Uri.fromFile(cutfile);


            mCutUri = outputUri;
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", true);
            // aspectX,aspectY 是宽高的比例，这里设置正方形
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            //设置要裁剪的宽高
            intent.putExtra("outputX", UIUtils.dip2px(200)); //200dp
            intent.putExtra("outputY", UIUtils.dip2px(200));
            intent.putExtra("scale", true);
            //如果图片过大，会导致oom，这里设置为false
            intent.putExtra("return-data", false);
            if (imageUri != null) {
                intent.setDataAndType(imageUri, "image/*");
            }
            if (outputUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            }
            intent.putExtra("noFaceDetection", true);
            //压缩图片
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            return intent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 拍照之后，启动裁剪
     *
     * @param camerapath 路径
     * @param imgname    img 的名字
     * @return
     */
    @NonNull
    private Intent CutForCamera(String camerapath, String imgname) {
        try {

            //设置裁剪之后的图片路径文件
            File cutfile = new File(Environment.getExternalStorageDirectory().getPath(),
                    "cutcamera.png"); //随便命名一个
            if (cutfile.exists()) { //如果已经存在，则先删除,这里应该是上传到服务器，然后再删除本地的，没服务器，只能这样了
                cutfile.delete();
            }
            cutfile.createNewFile();
            //初始化 uri
            Uri imageUri = null; //返回来的 uri
            Uri outputUri = null; //真实的 uri
            Intent intent = new Intent("com.android.camera.action.CROP");
            //拍照留下的图片
            File camerafile = new File(camerapath, imgname);
            if (Build.VERSION.SDK_INT >= 24) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                imageUri = FileProvider.getUriForFile(UserinfoActivity.this,
                        AppConst.PORVIDER,
                        camerafile);
            } else {
                imageUri = Uri.fromFile(camerafile);
            }
            outputUri = Uri.fromFile(cutfile);
            //把这个 uri 提供出去，就可以解析成 bitmap了
            mCutUri = outputUri;
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", true);
            // aspectX,aspectY 是宽高的比例，这里设置正方形
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            //设置要裁剪的宽高
            intent.putExtra("outputX", UIUtils.dip2px(200));
            intent.putExtra("outputY", UIUtils.dip2px(200));
            intent.putExtra("scale", true);
            //如果图片过大，会导致oom，这里设置为false
            intent.putExtra("return-data", false);
            if (imageUri != null) {
                intent.setDataAndType(imageUri, "image/*");
            }
            if (outputUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            }
            intent.putExtra("noFaceDetection", true);
            //压缩图片
            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
            return intent;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @OnClick({R.id.id_iv_av, R.id.ly_name, R.id.ly_sign, R.id.id_iv_av_more})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.id_iv_av:
            case R.id.id_iv_av_more:
                // cameraPic();
                requestPermission(new PermissionListener() {
                    @Override
                    public void onGranted() {
                        // T_.showToastReal("成功");
                        gotoSelectPhotoType();
                    }

                    @Override
                    public void onDenied(List<String> list) {
                        //T_.showToastReal("拒绝");
                    }
                }, Permission.Group.STORAGE);


                break;
            case R.id.ly_name:
                bundle.putInt("subType", UPDATA_USER_NAME);
                bundle.putString("content", idTvName.getText().toString());
                openActivity(UpdateActivity.class, bundle);
                break;
            case R.id.ly_sign:
                bundle.putInt("subType", UPDAT_USER_SGIN);
                bundle.putString("content", ivTvSign.getText().toString());
                openActivity(UpdateActivity.class, bundle);
                break;
        }
    }


    private void gotoSelectPhotoType() {


        int chooseMode = PictureMimeType.ofImage();
        // 进入相册 以下是例子：不需要的api可以不写
        PictureSelector.create(UserinfoActivity.this)
                .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(4)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .enableCrop(false)// 是否裁剪
                .compress(true)// 是否压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(false)// 是否圆形裁剪
                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .openClickSound(false)// 是否开启点击声音
                //.selectionMedia(false)// 是否传入已选图片
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }


}
